/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-03-01 14:39:27
 * @LastEditors: huangtianyang
 * @FilePath: \cxl-h5\src\pages\report\collision\index.ts
 */
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
import scrollIntoView from 'smooth-scroll-into-view-if-needed'
import Styler from 'stylefire'
import { animate } from 'popmotion'
import icon_paoshui from '@/assets/images/icon_paoshui.png'
import icon_guohuo from '@/assets/images/icon_guohuo.png'
import icon_anquanqinang from '@/assets/images/icon_anquanqinang.png'
import icon_waiguan from '@/assets/images/icon_waiguan.png'
import icon_gujia from '@/assets/images/icon_gujia.png'
import icon_jiaqiangjian from '@/assets/images/icon_jiaqiangjian.png'
import icon_biansuxiang from '@/assets/images/icon_biansuxiang.png'
import { useRoute } from 'vue-router'
import { getReportDetailed, vinParse } from '@/apis/report'
import useWeixinSdk from '@/utils/WXSdk'
import HistogramChart from '@/utils/chart/histogramChart'

//明细检查
interface DetailedCheckParams {
    [propName: string]: { value: string | number; list: any[] }
}
//车况异常项
interface abnormalParams {
    [propName: string]: any[]
}

//基本信息
interface basicParams {
    [propName: string]: any[] | string
}
//折线图弹窗
interface listParams {
    label: string
    value: string
}
interface lineChartDialogParams {
    visible: boolean
    list: listParams[]
}
interface columnParams {
    key: string // key
    blockClassName: string //最外层的classname
    bodyClassName: string //内容部分的classname
    name: string //标题
    icon: boolean //是否显示 小三角
    hint: string //文本提示
    abnormal: boolean //是否展示异常项数据
    abnormalCount: number //异常项数
    spread: boolean //是否展开内容
}

export class ReportDetailed {
    //是否显示顶部的tab
    tabVisible = ref(false)
    tab = reactive(['基础信息', '风险提示', '外观展示', '明细检查'])
    tabScrollTop: number[] = []
    tabSkipAnchor = ['.car-base-block', '.fxts', '.appearance-container', '.detailedCheck-container']
    selectTabIndex = ref(0)
    //选择查看的锚点
    selectTypeIndex = ref(0)
    //基本信息
    baseInfo = reactive({
        brandLogo: '',
        carName: '',
        expireTime: '',
        generateTime: '',
        id: '',
        orderNo: '',
        reportNo: '',
        vin: '',
        plateNo: '',
        bodyColor: '',
        licensePlateColor: '',
        models: '',
        brandname: '',
        fuelType: '',
        displacement: ''
    })
    //风险提示点
    fxtsList = reactive([
        { icon: icon_paoshui, text: '泡水检查', status: 0, targetClassName: '' },
        { icon: icon_guohuo, text: '过火检查', status: 0, targetClassName: '' },
        { icon: icon_anquanqinang, text: '安全气囊检查', status: 0, targetClassName: '' },
        { icon: icon_waiguan, text: '外观检查', status: 0, targetClassName: '' },
        { icon: icon_jiaqiangjian, text: '加强件检查', status: 0, targetClassName: '' },
        { icon: icon_gujia, text: '骨架检查', status: 0, targetClassName: '' },
        { icon: icon_biansuxiang, text: '发动机/变速箱检查', status: 0, targetClassName: '' }
    ])
    //外观展示点 front back right left center top bottom
    pointList = reactive([
        { checked: false, type: 'f', text: '前部', avtive: false },
        { checked: false, type: 'rf', text: '右前', avtive: false },
        { checked: false, type: 'rc', text: '右中', avtive: false },
        { checked: false, type: 'rb', text: '右后', avtive: false },
        { checked: false, type: 'b', text: '后部', avtive: false },
        { checked: false, type: 'lb', text: '左后', avtive: false },
        { checked: false, type: 'lc', text: '左中', avtive: false },
        { checked: false, type: 'lf', text: '左前', avtive: false },
        { checked: false, type: 'top', text: '顶部', avtive: false },
        { checked: false, type: 'bottom', text: '底部', avtive: false },
        { checked: false, type: 'inside', text: '内部', avtive: false }
    ])
    //基础信息
    basicInformation = reactive<basicParams>({
        //生产厂商
        manufacturers: [],
        //生产日期
        productionDate: '',
        //所在地区
        //初次登记日期
        registerDate: '',
        //当前使用性质
        properties: '',
        //是否有营业记录
        isBusiness: '',
        //是否有非个人车主情况
        isNoTown: '',
        //车主任数
        ownerNumber: '',
        //车辆使用年限
        //燃料类型
        fuelType: '',
        //排放标准
        emissionStandard: '',
        //排量
        vehicledisplacement: '',
        //国产/进口
        classattribute: ''
    })
    //配置信息（燃油车）
    configureInformation = reactive({
        //座位数
        // ratedpasscapa: '',
        //车身颜色
        bodyColor: '',
        //发动机号
        engineNo: '',
        //变速箱
        transmissionType: '',
        //长*宽*高
        carSize: '',
        //上市年月
        listingTime: ''
    })
    //配置信息（新能源车况车）
    configureInformationNEV = reactive({
        //座位数
        // ratedpasscapa: '',
        //车身颜色
        bodyColor: '',
        //发动机号
        engineNo: '',
        //排量
        //国产/进口
        vehicleAttributes: '',
        //驱动电机数
        motorNum: '',
        //续航里程
        biggestMileage: '',
        //电池组质保
        batteryWarranty: '',
        //电动机总功率（kw）
        totalPower: '',
        //电池能量（kwh）
        batteryEnergy: '',
        //百公里耗电量（kwh/100km）
        powerConsumptionPer: '',
        //长*宽*高
        carSize: '',
        //上市年月
        listingTime: ''
    })
    //保险信息
    insuranceInformation = reactive({
        //是否有有效交强险保单
        effectiveCpi: '',
        //是否有有效商业险保单
        effectiveCmi: '',
        //交强险是否连续投保
        seriesCoverCpi: '',
        //车损险是否连续投保
        isseriescoverCDR: '',
        isOutstandingCase: '', //是/否有未结案记录',
        isLogOut: '', //是/否有注销记录',
        isClaimsRejected: '' //是/否有拒赔记录'
    })
    //明细检查
    detailedCheck = reactive<DetailedCheckParams>({
        a: { value: 0, list: [] }, //地盘悬挂
        b: { value: 0, list: [] }, //发动机
        c: { value: 0, list: [] }, //附属配件
        d: { value: 0, list: [] }, //骨架
        e: { value: 0, list: [] }, //火烧
        f: { value: 0, list: [] }, //气囊
        g: { value: 0, list: [] }, //水淹
        h: { value: 0, list: [] }, //外观
        j: { value: 0, list: [] } //加强件
    })
    detailedCheckCount = ref(0)
    //保险tab
    insuranceTab = reactive(['未结案', '已结案'])
    //选择保险tab index
    selectBXTabIndex = ref(0)
    //保险记录
    insuranceRecorded: any[] = reactive([])
    //是否是在生产保险图片，保险记录全部展开
    insuranceDownload = ref(false)
    //报告id
    reportId = ref('')
    //分享提示弹窗
    shareDialogVisible = ref(false)
    //底部下载分享栏弹窗
    bottomFnVisible = ref(false)
    //是否显示返回顶部按钮
    goTopVisible = ref(false)
    //默认显示水印
    watermarkVisible = ref(false)
    //监听滚动元素
    scrollEl: any
    //屏幕的高度
    windowHeight = 0
    //内容区域高度
    contentHeight = ref(0)
    //是否是分享进入
    isShare = ref(false)
    //是否显示下载图片弹窗
    downloadImageVisible = ref(false)
    //需要保存的图片
    downloadImageUrl = ref('')
    //生成图片加载过程loading
    loadingVisible = ref(false)
    //vin id
    vinParseId = ref('')
    //车牌颜色
    bodyColor = ref(0)
    //风险提示距离顶部距离
    fxtsScrollTop = ref(0)
    //外观展示距离顶部距离
    wgzsScrollTop = ref(0)
    //明细检查距离顶部距离
    mxjjScrollTop = ref(0)
    fromCase = ref(false)
    //外观异常数
    appearanceAbnormalCount = ref(0)
    //保险统计
    insuranceStatistics = reactive([
        { label: '事故总次数', value: '', visible: true, anchor: '.insurance-record' },
        { label: '事故损失总金额', value: '', visible: true, anchor: '' },
        { label: '最大维修金额', value: '', visible: true, anchor: '' },
        { label: '已结案次数', value: '', visible: true, anchor: '.close-case' },
        { label: '未结案次数', value: '', visible: true, anchor: '.no-close-case' },
        { label: '拒赔次数', value: '', visible: true, anchor: '' }
    ])
    //外观异常统计
    abnormal = reactive<abnormalParams>({
        appearance: [], //外观
        reinforcer: [], //加强件
        detailedCheck: [] //明细检查
    })
    //基本信息是否折叠
    baseInfoSpread = ref(true)
    //配置信息是否折叠
    configInfoSpread = ref(true)
    //报告类型 1出险 2 维保车况 3新能源车况
    reportType = ref('1')
    //折线图
    xAxis: number[] = reactive([]) //次数
    count: number[] = reactive([]) //金额
    yAxis: number[] = reactive([]) //年
    lineChartDialog = reactive<lineChartDialogParams>({
        visible: false,
        list: [
            { label: '事故次数', value: '0次' },
            { label: '维修总金额', value: '0元' },
            { label: '最大维修金额', value: '0元' },
            { label: '已结案次数', value: '0次' },
            { label: '拒赔次数', value: '0次' },
            { label: '注销次数', value: '0次' },
            { label: '未结案次数', value: '0次' }
        ]
    })
    //骨架图
    skeletonImageUrl = ref('')
    //对应的栏目是否展开
    columnArray = reactive<columnParams[]>([
        {
            key: '',
            blockClassName: 'car-base-block',
            bodyClassName: '',
            name: '基础信息',
            icon: true,
            hint: '',
            abnormal: false,
            abnormalCount: 0,
            spread: true
        },
        {
            key: '',
            blockClassName: '',
            bodyClassName: '',
            name: '配置信息',
            icon: true,
            hint: '',
            abnormal: false,
            abnormalCount: 0,
            spread: true
        },
        {
            key: '',
            blockClassName: 'fxts',
            bodyClassName: '',
            name: '风险提示',
            icon: false,
            hint: '红色表示异常，绿色则为正常',
            abnormal: false,
            abnormalCount: 0,
            spread: true
        },
        {
            key: '',
            blockClassName: 'appearance-container abnormalHint',
            bodyClassName: 'wgzs',
            name: '外观展示',
            icon: false,
            hint: '',
            abnormal: true,
            abnormalCount: 0,
            spread: true
        },
        {
            key: '',
            blockClassName: '',
            bodyClassName: '',
            name: '骨架加强件检查',
            icon: false,
            hint: '',
            abnormal: false,
            abnormalCount: 0,
            spread: true
        },
        {
            key: '',
            blockClassName: 'detailedCheck-container  abnormalHint',
            bodyClassName: '',
            name: '明细检查',
            icon: false,
            hint: '',
            abnormal: true,
            abnormalCount: 0,
            spread: true
        },
        {
            key: '',
            blockClassName: '',
            bodyClassName: '',
            name: '保险信息',
            icon: false,
            hint: '',
            abnormal: false,
            abnormalCount: 0,
            spread: true
        },
        {
            key: '',
            blockClassName: '',
            bodyClassName: '',
            name: '保险事故',
            icon: false,
            hint: '',
            abnormal: false,
            abnormalCount: 0,
            spread: true
        }
    ])
    //报告查询失败
    reportQueryFail = ref(false)
    //报告过期
    reportExpire = ref(false)
    //报告是否加载完成
    reportLoad = ref(false)
    constructor() {
        const router = useRoute()
        this.reportId.value = router.query.reportId as string
        this.vinParseId.value = router.query.vinParseId as string
        if (router.query.share as string) {
            console.log('share')
            this.isShare.value = true
        }
        const type = ref('')
        type.value = (router.query.type as string) ?? ''
        this.fromCase.value = type.value ? true : false
        this.reportType.value = router.query.productType as string

        this.windowHeight = window.innerHeight

        console.log('router.query', router.query)

        Promise.all([
            vinParse(this.vinParseId.value), //vin码解析数据查询
            getReportDetailed(this.reportId.value) //报告详细信息
        ]).then(res => {
            if (res[1].data.value === 7003) {
                ///报告过期
                this.reportExpire.value = true
            } else if (res[0].data.value !== 200 && res[1].data.value !== 200) {
                this.reportQueryFail.value = true
            }
            //vin 解析返回的数据
            let vinParseResult = null
            if (res[0].data.value === 200) {
                vinParseResult = res[0].data.data
                console.log('vin 解析返回的数据', vinParseResult)
                //vin
                this.baseInfo.vin = vinParseResult.vin
                //车型
                this.baseInfo.models = vinParseResult.modelDetail
            }
            if (res[1].data.value === 200) {
                console.log('报告详细信息', res[1].data.data)
                //外观受损位置 车辆损失方位总结
                const vehicleDamagePosition = res[1].data.data.vehicleDamagePosition
                console.log('车辆损失方位总结', vehicleDamagePosition)
                //车况大类检查 车况排查（大类)
                const vehicleConditionCheck = res[1].data.data.vehicleConditionCheck
                console.log('车况排查（大类)', vehicleConditionCheck)
                //保险详情 出险记录
                const insurance = res[1].data.data.collisionDetailRecords
                console.log('出险记录', insurance)
                //保险信息
                const vehicleConditionInformation = res[1].data.data.vehicleConditionInformation
                console.log('保险信息', vehicleConditionInformation)
                //保险统计
                const accidentStatistics = res[1].data.data.accidentStatistics
                //保险折线图数据
                const collisionDetailYearAmountCount = res[1].data.data.collisionDetailYearAmountCount
                //明细检查
                const vehicleConditionCheckList = res[1].data.data.vehicleConditionCheckList

                //
                const info = {
                    ...res[1].data.data.reportDetails, //报告基本信息
                    ...res[1].data.data.vehicleLicenseInfo, //行驶证解析的信息
                    ...res[1].data.data.vehicleInformation //车辆基本信息
                }
                console.log('info', info)

                /**
                 * 报告基本信息
                 */

                this.baseInfo.id = info.id
                this.baseInfo.orderNo = info.orderNo
                this.baseInfo.reportNo = info.reportNo

                //车名
                this.baseInfo.carName = vinParseResult.brand || info.carName
                //报告到期时间
                this.baseInfo.expireTime = info.expireTime
                //报告生成时间
                this.baseInfo.generateTime = info.generateTime
                //车牌号
                this.baseInfo.plateNo = info.plateNo

                //车标
                this.baseInfo.brandLogo = vinParseResult.brandLogo || info.brandNameUrl
                //vin
                this.baseInfo.vin = info.vin
                //车牌颜色 (1.绿牌；2.蓝牌；3.其他)
                this.baseInfo.licensePlateColor = vinParseResult.licensePlateColor + ''
                //车型
                this.baseInfo.models = vinParseResult.modelDetail || info.model
                //品牌
                this.baseInfo.brandname = vinParseResult.brand || info.brandName
                //车牌颜色
                this.bodyColor.value = Number(info.licensePlateColor)
                //动力类型
                this.baseInfo.fuelType = vinParseResult.fuelType
                //排量
                this.baseInfo.displacement = vinParseResult.displacement

                /**
                 * 骨架截图
                 */
                this.skeletonImageUrl.value = info.skeletonImageUrl

                /**
                 * 风险点提示
                 *  0正常，1 无法确定 2 疑似,3 维保异常，4 出险异常
                 */
                //泡水检查
                this.fxtsList[0].status = Number(vehicleConditionCheck.flooding)
                //过火检查
                this.fxtsList[1].status = Number(vehicleConditionCheck.fire)
                //安全气囊检查
                this.fxtsList[2].status = Number(vehicleConditionCheck.gasbag)
                //外观检查
                this.fxtsList[3].status = Number(vehicleConditionCheck.appearance)
                //加强件检查
                this.fxtsList[4].status = Number(vehicleConditionCheck.stiffener)
                //骨架检查
                this.fxtsList[5].status = Number(vehicleConditionCheck.skeleton)
                //发动机/变速箱检查
                this.fxtsList[6].status = Number(vehicleConditionCheck.gearbox)

                /**
                 * 外观展示
                 * 0无受损 1有受损
                 */
                //前部
                this.pointList[0].checked = Number(vehicleDamagePosition.front) === 0 ? false : true
                //右前
                this.pointList[1].checked = Number(vehicleDamagePosition.frontRight) === 0 ? false : true
                //右中
                this.pointList[2].checked = Number(vehicleDamagePosition.centerRight) === 0 ? false : true
                //右后
                this.pointList[3].checked = Number(vehicleDamagePosition.rearRight) === 0 ? false : true
                //后部
                this.pointList[4].checked = Number(vehicleDamagePosition.rear) === 0 ? false : true
                //左后
                this.pointList[5].checked = Number(vehicleDamagePosition.rearLeft) === 0 ? false : true
                //左中
                this.pointList[6].checked = Number(vehicleDamagePosition.centerLeft) === 0 ? false : true
                //左前
                this.pointList[7].checked = Number(vehicleDamagePosition.frontLeft) === 0 ? false : true
                //顶部
                this.pointList[8].checked = Number(vehicleDamagePosition.top) === 0 ? false : true
                //底部
                this.pointList[9].checked = Number(vehicleDamagePosition.bottom) === 0 ? false : true
                //内部
                this.pointList[10].checked = Number(vehicleDamagePosition.inside) === 0 ? false : true

                //统计外观异常数
                for (const key in vehicleDamagePosition) {
                    console.log(vehicleDamagePosition[key], key)
                    if (vehicleDamagePosition[key] !== 0) {
                        this.appearanceAbnormalCount.value++
                    }
                }
                this.columnArray[3].abnormalCount = this.appearanceAbnormalCount.value
                //统计异常项中的外观
                this.abnormal.appearance.length = 0
                this.pointList.forEach(item => {
                    if (item.checked) {
                        this.abnormal.appearance.push(item.text)
                    }
                })

                /**
                 * 基础信息
                 */
                //生产厂商
                this.basicInformation.manufacturers = vinParseResult.manufacturers
                //生产日期
                this.basicInformation.productionDate = info.productionDate
                //初次登记日期
                this.basicInformation.registerDate = info.registerDate
                //当前使用性质
                this.basicInformation.properties = info.properties
                //是否有营业记录
                this.basicInformation.isBusiness = Number(info.isBusiness) ? '是' : '否'
                //是否有非个人车主情况
                this.basicInformation.isNoTown = Number(info.isNoTown) ? '是' : '否'
                //车主任数
                this.basicInformation.ownerNumber = info.ownerNumber
                //排放标准
                this.basicInformation.emissionStandard = vinParseResult.emissionStandard
                //排量
                this.basicInformation.vehicledisplacement = vinParseResult.displacement
                //国产/进口
                this.basicInformation.classattribute = vinParseResult.vehicleAttributes
                //燃料类型
                this.basicInformation.fuelType = vinParseResult.fuelType

                /**
                 * 配置信息燃油车
                 */
                //座位数
                // this.configureInformation.ratedpasscapa = info.ratedpasscapa
                //车身颜色
                this.configureInformation.bodyColor = info.bodyColor
                //变速箱
                this.configureInformation.transmissionType = vinParseResult.transmissionType
                //长*宽*高
                this.configureInformation.carSize = vinParseResult.carSize
                //上市年月
                this.configureInformation.listingTime = vinParseResult.listingTime
                //发动机号码
                this.configureInformation.engineNo = info.engineNo

                /**
                 * 配置信息新能源车况车
                 */
                //座位数
                // this.configureInformationNEV.ratedpasscapa = info.ratedpasscapa
                //车身颜色
                this.configureInformationNEV.bodyColor = info.bodyColor
                //国产/进口
                this.configureInformationNEV.vehicleAttributes = info.vehicleAttributes
                //驱动电机数
                this.configureInformationNEV.motorNum = info.motorNum
                //续航里程
                this.configureInformationNEV.biggestMileage = info.biggestMileage
                //电池组质保
                this.configureInformationNEV.batteryWarranty = info.batteryWarranty
                //电动机总功率（kw）
                this.configureInformationNEV.totalPower = info.totalPower
                //电池能量（kwh）
                this.configureInformationNEV.batteryEnergy = info.batteryEnergy
                //百公里耗电量（kwh/100km）
                this.configureInformationNEV.powerConsumptionPer = info.powerConsumptionPer
                //长*宽*高
                this.configureInformationNEV.carSize = vinParseResult.carSize
                //上市年月
                this.configureInformationNEV.listingTime = vinParseResult.listingTime
                //发动机号码
                this.configureInformationNEV.engineNo = info.engineNo

                /**
                 * 保险信息
                 */
                //是否有有效交强险保单 0否 1是
                this.insuranceInformation.effectiveCpi = vehicleConditionInformation.effectiveCpi ? '是' : '否'
                //是否有有效商业险保单 0否 1是
                this.insuranceInformation.effectiveCmi = vehicleConditionInformation.effectiveCmi ? '是' : '否'
                //交强险是否连续投保  0多张保单短时间非连续投保 1多张保单连续投保 2单张保单 3 无交强险保单记录 4 多张保单长时间非连续投保
                const t = [
                    '多张保单短时间非连续投保',
                    '多张保单连续投保',
                    '单张保单',
                    '无交强险保单记录',
                    '多张保单长时间非连续投保'
                ]
                this.insuranceInformation.seriesCoverCpi = t[Number(vehicleConditionInformation.seriesCoverCpi)]
                //车损险是否连续投保
                this.insuranceInformation.isseriescoverCDR = vehicleConditionInformation.isseriescoverCDR
                //是/否有未结案记录'
                this.insuranceInformation.isOutstandingCase =
                    Number(accidentStatistics.claimUnCacCount) > 0 ? '是' : '否'
                //是/否有注销记录'
                this.insuranceInformation.isLogOut = Number(accidentStatistics.writeOffCount) > 0 ? '是' : '否'
                //是/否有拒赔记录'
                this.insuranceInformation.isClaimsRejected =
                    Number(accidentStatistics.claimRejectedCount) > 0 ? '是' : '否'

                /**
                 * 保险事故
                 */
                //保险记录 已结案
                this.insuranceRecorded.length = 0
                insurance.forEach((item: any) => {
                    //claimType 类型 1商业险 2交强险
                    this.insuranceRecorded.push(item)
                })

                //保险统计
                //事故总次数
                this.insuranceStatistics[0].value = accidentStatistics.claimCount
                //事故损失总金额
                this.insuranceStatistics[1].value = '≈' + accidentStatistics.totalAmount + '元'
                //最大维修金额
                this.insuranceStatistics[2].value = '≈' + accidentStatistics.largestAmount + '元'
                //已结案次数
                this.insuranceStatistics[3].value = accidentStatistics.claimCacCount
                //未结案次数
                this.insuranceStatistics[4].value = accidentStatistics.claimUnCacCount
                //拒赔次数
                this.insuranceStatistics[5].value = accidentStatistics.claimRejectedCount

                //保险弹窗数据
                this.lineChartDialog.list[0].value = this.insuranceRecorded.length + '次' //事故次数
                this.lineChartDialog.list[1].value = '≈' + accidentStatistics.totalAmount + '元' //维修总金额
                this.lineChartDialog.list[2].value = '≈' + accidentStatistics.largestAmount + '元' //最大维修金额
                this.lineChartDialog.list[3].value = accidentStatistics.claimCacCount + '次' //已结案次数
                this.lineChartDialog.list[4].value = accidentStatistics.claimRejectedCount + '次' //拒赔次数
                this.lineChartDialog.list[5].value = accidentStatistics.writeOffCount + '次' //注销次数
                this.lineChartDialog.list[6].value = accidentStatistics.claimUnCacCount + '次' //未结案次数

                /**
                 * 明细检查
                 * "1 底盘悬挂相关排查记录
                 * "2 发动机相关排查记录
                 * "3 附属配件相关排查记录
                 * "4 骨架相关排查记录"
                 * "5 火烧相关排查记录三
                 * "6 加强件相关排查记录
                 * "7 气囊相关排查记录
                 * "8 水淹相关排查记录
                 * "9 外观相关排查记录
                 */
                //首先清空数据
                for (const key in this.detailedCheck) {
                    this.detailedCheck[key].value = 0
                    this.detailedCheck[key].list.length = 0
                }

                this.abnormal.detailedCheck.length = 0
                this.detailedCheckCount.value = 0
                for (const key in vehicleConditionCheckList) {
                    vehicleConditionCheckList[key].forEach((item: any) => {
                        this.abnormal.detailedCheck.push(item.name)
                    })

                    this.detailedCheckCount.value++

                    this.columnArray[5].abnormalCount = this.detailedCheckCount.value

                    if (Number(key) === 1) {
                        //地盘悬挂
                        this.detailedCheck.a.value = 1
                        this.detailedCheck.a.list = [...vehicleConditionCheckList[key]]
                    } else if (Number(key) === 2) {
                        //发动机
                        this.detailedCheck.b.value = 1
                        this.detailedCheck.b.list = [...vehicleConditionCheckList[key]]
                    } else if (Number(key) === 3) {
                        //附属配件
                        this.detailedCheck.c.value = 1
                        this.detailedCheck.c.list = [...vehicleConditionCheckList[key]]
                    } else if (Number(key) === 4) {
                        //骨架
                        this.detailedCheck.d.value = 1
                        this.detailedCheck.d.list = [...vehicleConditionCheckList[key]]
                    } else if (Number(key) === 5) {
                        //火烧
                        this.detailedCheck.e.value = 1
                        this.detailedCheck.e.list = [...vehicleConditionCheckList[key]]
                    } else if (Number(key) === 6) {
                        //加强件
                        this.detailedCheck.j.value = 1
                        this.detailedCheck.j.list = [...vehicleConditionCheckList[key]]
                        this.abnormal.reinforcer.length = 0
                        this.detailedCheck.j.list.forEach(item => {
                            this.abnormal.reinforcer.push(item.name)
                        })
                    } else if (Number(key) === 7) {
                        //气囊
                        this.detailedCheck.f.value = 1
                        this.detailedCheck.f.list = [...vehicleConditionCheckList[key]]
                    } else if (Number(key) === 8) {
                        //水淹
                        this.detailedCheck.g.value = 1
                        this.detailedCheck.g.list = [...vehicleConditionCheckList[key]]
                    } else if (Number(key) === 9) {
                        //外观
                        this.detailedCheck.h.value = 1
                        this.detailedCheck.h.list = [...vehicleConditionCheckList[key]]
                    }
                }

                this.xAxis.length = 0
                this.count.length = 0
                this.yAxis.length = 0
                for (const key in collisionDetailYearAmountCount) {
                    this.xAxis.push(collisionDetailYearAmountCount[key][0])
                    this.count.push(collisionDetailYearAmountCount[key][1])
                    this.yAxis.push(Number(key))
                }
                //判断返回的数据有多少个 至少得5年
                const n = 5
                let maxYear = 0
                let minYear = 0
                let next = 4 //maxYear 往后加4年
                let prev = 0 //maxYear 往前加0年
                if (this.yAxis.length < n) {
                    maxYear = Math.max(...this.yAxis)
                    minYear = Math.min(...this.yAxis)

                    //用最大的年份和当前的年份进行对比
                    const oDate = new Date()
                    const currentYear = oDate.getFullYear()
                    console.log('currentYear', currentYear, 'maxYear', maxYear)
                    //得到maxyear年距离现在年的差值
                    next = currentYear - maxYear
                    //假如next差值+yAxis的长度 大于默认 5，则prev=0
                    prev = next + this.yAxis.length >= n ? 0 : n - next - this.yAxis.length

                    for (let i = 0; i < next; i++) {
                        this.yAxis.push((maxYear += 1))
                        this.count.push(0)
                        this.xAxis.push(0)
                    }
                    for (let i = 0; i < prev; i++) {
                        this.yAxis.unshift((minYear -= 1))
                        this.count.unshift(0)
                        this.xAxis.unshift(0)
                    }
                }
                maxYear = Math.max(...this.yAxis)
                minYear = Math.min(...this.yAxis)

                this.xAxis.length = 0
                this.count.length = 0
                this.yAxis.length = 0
                for (let i = minYear; i <= maxYear; i++) {
                    this.xAxis.push(collisionDetailYearAmountCount[i + ''] ? collisionDetailYearAmountCount[i][0] : 0)
                    this.count.push(collisionDetailYearAmountCount[i + ''] ? collisionDetailYearAmountCount[i][1] : 0)
                    this.yAxis.push(Number(i))
                }

                console.log(this.xAxis, this.count, this.yAxis)
                new HistogramChart('.insurance-container', this.xAxis, this.count, this.yAxis)

                //生成水印
                this.watermarkVisible.value = true

                //报告加载完成
                this.reportLoad.value = true

                //分享设置
                if (!this.fromCase.value) {
                    useWeixinSdk.shareReport({
                        title:
                            this.baseInfo.plateNo && this.baseInfo.plateNo.length > 6
                                ? this.baseInfo.plateNo + '的车况报告'
                                : this.baseInfo.brandname + '车型的车况报告',
                        desc: `vin：${this.baseInfo.vin}\r\n生成时间：${this.baseInfo.generateTime}`,
                        link: window.location.href + '&share=true',
                        imgUrl: this.baseInfo.brandLogo
                    })
                }

                this.getAnchorScrollTop()
            }
        })

        onMounted(() => {
            // editPageTitle('车辆出险车况报告')

            if (this.isShare.value) {
                useWeixinSdk.disableShare()
            } else {
                useWeixinSdk.ableShare()
            }
            if (!this.reportQueryFail.value) {
                this.scrollEl = document.querySelector('.report-main') as HTMLElement
                this.contentHeight.value = (document.querySelector('#report') as HTMLElement).offsetHeight
                this.scrollEl?.addEventListener('scroll', this.onScroll, false)
            }
        })
        onUnmounted(() => {
            this.scrollEl?.addEventListener('scroll', this.onScroll, false)
        })
    }
    //获取tab滚动点距离顶部的距离
    getAnchorScrollTop() {
        this.tabScrollTop.length = 0
        const timer = setTimeout(() => {
            this.tabSkipAnchor.forEach(item => {
                const ele = document.querySelector(item) as HTMLElement
                console.log(item, ele.offsetTop)
                this.tabScrollTop.push(ele.offsetTop)
            })
            clearTimeout(timer)
        }, 10)
    }
    //监听滚动
    onScroll = () => {
        console.log(this.scrollEl?.scrollTop, this.tabScrollTop)
        //判断当前是否是在生成图片
        if (this.downloadImageVisible.value) {
            return
        }
        if (this.scrollEl?.scrollTop >= this.windowHeight / 8) {
            //大于屏幕的1/8
            //顶部的导航出现
            if (!this.tabVisible.value) {
                this.tabVisible.value = true
                console.log('visible')
            }
        } else {
            if (this.tabVisible.value) {
                this.tabVisible.value = false
            }
        }
        if (this.scrollEl?.scrollTop >= this.windowHeight / 2) {
            //大于屏幕的一半
            //返回顶部按钮出现
            if (!this.goTopVisible.value) {
                this.goTopVisible.value = true
            }
        } else {
            if (this.goTopVisible.value) {
                this.goTopVisible.value = false
            }
        }
        if (this.scrollEl?.scrollTop >= this.contentHeight.value - this.windowHeight * 1.5 && !this.fromCase.value) {
            //底部按钮出现
            if (!this.bottomFnVisible.value) {
                this.bottomFnVisible.value = true
            }
        } else {
            if (this.bottomFnVisible.value) {
                this.bottomFnVisible.value = false
            }
        }
        //根据滚动的内容设置顶部导航的位置
        if (this.scrollEl?.scrollTop < this.tabScrollTop[1] - 50) {
            if (this.selectTabIndex.value !== 0) {
                this.selectTabIndex.value = 0
            }
        } else if (
            this.scrollEl?.scrollTop >= this.tabScrollTop[1] - 50 &&
            this.scrollEl?.scrollTop < this.tabScrollTop[2] - 50
        ) {
            if (this.selectTabIndex.value !== 1) {
                this.selectTabIndex.value = 1
            }
        } else if (
            this.scrollEl?.scrollTop >= this.tabScrollTop[2] - 50 &&
            this.scrollEl?.scrollTop < this.tabScrollTop[3] - 50
        ) {
            if (this.selectTabIndex.value !== 2) {
                this.selectTabIndex.value = 2
            }
        } else {
            if (this.selectTabIndex.value !== 3) {
                this.selectTabIndex.value = 3
            }
        }
    }
    onSelectTab = (index: number) => {
        const box = document.querySelector(this.tabSkipAnchor[index]) as HTMLElement
        const tab = document.querySelector('.tab') as HTMLElement

        console.log('this.tabSkipAnchor[index]', index, this.tabSkipAnchor[index])

        scrollIntoView(box, {
            behavior: instructions => {
                const [{ el, top }] = instructions
                const styler = Styler(el)

                animate({
                    from: el.scrollTop,
                    to: top - tab.offsetHeight,
                    type: 'keyframes',
                    onUpdate: (y: number) => styler.set('scrollTop', y)
                })
            },
            block: 'start',
            inline: 'end'
        })
    }
    //监听选择查看保险
    onSelectBXTab = (index: number) => {
        this.selectBXTabIndex.value = index
        nextTick(() => {
            this.contentHeight.value = (document.querySelector('#report') as HTMLElement).offsetHeight
            this.getAnchorScrollTop()
        })
        //100毫秒后重新生成水印
        this.watermarkVisible.value = false
        const timer = setTimeout(() => {
            this.watermarkVisible.value = true
            clearTimeout(timer)
        }, 10)
    }
    //返回顶部
    goTop = () => {
        this.selectTypeIndex.value = 0
    }
    //下载报告-显示保存图片弹窗
    startDownload = () => {
        //开始生成图片
        this.downloadImageVisible.value = true
        //隐藏顶部tab
        this.tabVisible.value = false
        //展开保险记录所有的列
        this.insuranceDownload.value = true
        //基础信息展开
        this.baseInfoSpread.value = true
        //配置信息展开
        this.configInfoSpread.value = true
        //外观展示 所有的的点全部显示出来
        this.pointList.forEach(item => {
            if (item.checked) {
                item.avtive = true
            }
        })
        //所有栏目默认展开
        this.columnArray.forEach((item: columnParams) => {
            item.spread = true
        })

        // const box = document.querySelector('.car-info') as HTMLElement
        // scrollIntoView(box, {
        //     scrollMode: 'if-needed',
        //     behavior: 'smooth'
        // })
    }
    //点击隐藏下载弹窗
    hideDownload = () => {
        this.downloadImageVisible.value = false
        this.tabVisible.value = true
        this.insuranceDownload.value = false
        this.pointList.forEach(item => {
            if (item.checked) {
                item.avtive = false
            }
        })
    }
    //点击风险提示点，进行跳转到明细检查
    onClick = (index: number) => {
        if (this.fxtsList[index].status === 4) {
            this.onSkipAnchor('.detailedCheck-container')
        }
    }
    //点击外观的点
    onClickApprearancePoint = (index: number) => {
        console.log(index, this.pointList[index])
        if (this.pointList[index].checked) {
            this.pointList[index].avtive = !this.pointList[index].avtive
        }
    }
    //点击 滚动 到指定位置
    onSkipAnchor(eleName: string) {
        if (!eleName) {
            return
        }
        const targetEle = document.querySelector(eleName) as HTMLElement
        if (!targetEle) {
            return
        }
        const tab = document.querySelector('.tab') as HTMLElement

        scrollIntoView(targetEle, {
            behavior: instructions => {
                const [{ el, top }] = instructions
                const styler = Styler(el)

                animate({
                    from: el.scrollTop,
                    to: top - tab.offsetHeight,
                    type: 'keyframes',
                    onUpdate: (y: number) => styler.set('scrollTop', y)
                })
            },
            block: 'start',
            inline: 'end'
        })
    }
    //信息项是否展开 1 基本信息 2 配置信息
    toggle = (index: number) => {
        this.columnArray[index].spread = !this.columnArray[index].spread
        nextTick(() => {
            this.contentHeight.value = (document.querySelector('#report') as HTMLElement).offsetHeight
            this.getAnchorScrollTop()
        })
    }
    //显示折线图弹窗/隐藏折线图弹窗
    onVisibleLineChartDialog = (type: string) => {
        if (type === 'show') {
            this.lineChartDialog.visible = true
            setTimeout(() => {
                new HistogramChart('.line-chart', this.xAxis, this.count, this.yAxis)
            }, 50)
        } else if (type === 'hide') {
            this.lineChartDialog.visible = false
        }
    }
}
